import React, { useState, useEffect, useRef } from 'react';
import ReactECharts from 'echarts-for-react';
import { Tabs } from 'antd';
import type { EChartsOption } from 'echarts';
import { getFinancialTrends, type FinancialTrendsResponse } from '@/api/modules/index';
import { useTranslation } from 'react-i18next';

interface FundTrendsData {
  xdata: string[];
  ydata: Array<{
    i18n_key: string;
    data: (number | string)[];
    color: string;
  }>;
}

interface FundTrendsProps {
  loading?: boolean;
}

const FundTrends: React.FC<FundTrendsProps> = ({ loading = false }) => {
  const { t } = useTranslation();
  const [activeName, setActiveName] = useState<'week' | 'month' | 'year'>('week');
  const [xdata, setXdata] = useState<string[]>([]);
  const [ydata, setYdata] = useState<FundTrendsData['ydata']>([]);
  const [internalLoading, setInternalLoading] = useState(false);
  const chartRef = useRef<ReactECharts>(null);

  // 真实数据获取
  useEffect(() => {
    const getData = async () => {
      setInternalLoading(true);
      try {
        const response = await getFinancialTrends(activeName);
        // 类型断言，因为axios拦截器返回的是数据而不是AxiosResponse
        const data = response as unknown as FinancialTrendsResponse;
        
        setXdata(data.xdata);
        setYdata(data.ydata);
      } catch (error) {
        console.error('获取资金趋势数据失败:', error);
      } finally {
        setInternalLoading(false);
      }
    };

    getData();
  }, [activeName]);


  // 解析数据为数字
  const parseData = (data: (number | string)[]): number[] => {
    return data.map(item => Number(item));
  };

  // 获取图表配置
  const getOption = (): EChartsOption => {
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
      },
      legend: {
        top: 8,
        left: 'center',
        orient: 'horizontal',
        itemGap: 24,
        itemWidth: 14,
        itemHeight: 14,
        textStyle: {
          fontSize: 12,
        },
      },
      grid: {
        top: 40,
        left: 0,
        right: 0,
        bottom: 0,
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: xdata,
        axisLabel: {
          color: '#666',
          margin: 8,
        },
        axisLine: {
          lineStyle: {
            color: '#ddd',
          },
        },
        axisTick: {
          show: false,
        },
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#666',
          formatter: (value: number) => value.toFixed(2),
          margin: 8,
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#eee',
          },
        },
        axisTick: {
          show: false,
        },
      },
      series: ydata.map(item => ({
        name: t(item.i18n_key),
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: item.color,
        },
        lineStyle: {
          color: item.color,
          width: 2,
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: `${item.color}40` },
              { offset: 1, color: `${item.color}00` },
            ],
          },
        },
        data: parseData(item.data),
      })),
    };
  };

  // 处理选项卡变化
  const handleTabChange = (key: string) => {
    setActiveName(key as 'week' | 'month' | 'year');
  };

  return (
    <div className="bg-white p-6 rounded-lg shadow">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold text-blue-800">{t('route.fund_manage.details')}</h2>
        <Tabs
          activeKey={activeName}
          onChange={handleTabChange}
          size="small"
          items={[
            { key: 'week', label: t('recent_1_week') },
            { key: 'month', label: t('recent_1_month') },
            { key: 'year', label: t('recent_1_year') },
          ]}
        />
      </div>
      <div className="min-h-70 w-full relative">
        {(loading || internalLoading) && (
          <div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-80 z-10">
            <div className="text-gray-500">{t('app.route.reload')}</div>
          </div>
        )}
        <ReactECharts
          ref={chartRef}
          option={getOption()}
          style={{ height: '280px', width: '100%' }}
          opts={{ renderer: 'canvas' }}
        />
      </div>
    </div>
  );
};

export default FundTrends;